# -*- coding: utf-8 -*-

import copy
import datetime
import gluon.contenttype
import gluon.fileutils

global_env = copy.copy(globals())

def index():
    response.headers['Content-Type'] = \
        gluon.contenttype.contenttype('.csv')

    id = request.args[0] if len( request.args ) else 0

    query = ( ( ( db.kioskContribution.fromWeb == False ) |
                ( db.kioskContribution.fromWeb == None ) ) &
              ( db.kioskContribution.approved == True ) &
              ( db.kioskContribution.id >= id ) )
    
    response.headers['Content-disposition'] = 'attachment; filename=%s_%s.csv'\
         % ( 'kioskContributionExport', datetime.datetime.now() )

    rv = [ str( db(query).select( db.kioskContribution.id,
                                  db.kioskContribution.firstName,
                                  db.kioskContribution.age,
                                  db.kioskContribution.hometown,
                                  db.kioskContribution.contribution,
                                  db.kioskContribution.question ) ) ]

    rv.insert( 0, "Id, First Name, Age, Hometown, Contribution, Question\n" )
    rv.insert( 0, "Question C : What scared you most about the events of 9/11?\n" )
    rv.insert( 0, "Question B : What image or object in this exhibition moved you most?  Why?\n" )
    rv.insert( 0, "Question A : Did the events of 9/11 change how you define a hero?\n" )

    return ''.join( rv )
            


# ##########################################################
# ## auxiliary functions
# ###########################################################


def get_databases(request):
    dbs = {}
    for (key, value) in global_env.items():
        cond = False
        try:
            cond = isinstance(value, GQLDB)
        except:
            cond = isinstance(value, SQLDB)
        if cond:
            dbs[key] = value
    return dbs


databases = get_databases(None)


def eval_in_global_env(text):
    exec ('_ret=%s' % text, {}, global_env)
    return global_env['_ret']


def get_database(request):
    if request.args and request.args[0] in databases:
        return eval_in_global_env(request.args[0])
    else:
        session.flash = T('invalid request')
        redirect(URL('index'))


def get_table(request):
    db = get_database(request)
    if len(request.args) > 1 and request.args[1] in db.tables:
        return (db, request.args[1])
    else:
        session.flash = T('invalid request')
        redirect(URL('index'))


def get_query(request):
    try:
        return eval_in_global_env(request.vars.query)
    except Exception:
        return None


def query_by_table_type(tablename,db,request=request):
    keyed = hasattr(db[tablename],'_primarykey')
    if keyed:
        firstkey = db[tablename][db[tablename]._primarykey[0]]
        cond = '>0'
        if firstkey.type in ['string', 'text']:
            cond = '!=""'
        qry = '%s.%s.%s%s' % (request.args[0], request.args[1], firstkey.name, cond)
    else:
        qry = '%s.%s.id>0' % tuple(request.args[:2])
    return qry
